package com.asiainfo.heshanghui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.asiainfo.heshanghui.adapter_recyclerview.UniversalAdapter;
import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.configs.InterfaceConfig;
import com.asiainfo.heshanghui.entity.SaleListInfo;
import com.asiainfo.heshanghui.entity.ScanInfo;
import com.asiainfo.heshanghui.networkModel.HttpUtil;
import com.asiainfo.heshanghui.other.CustomLinearLayoutManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.framework.Utils.PreferencesHelper;
import com.framework.Utils.RegularUtil;
import com.framework.Utils.ScreenUtils;
import com.framework.Utils.ToastUtil;
import com.framework.Utils.Utils;
import com.framework2.base.BaseOnClickListener;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.customview.TitleView;
import com.framework2.greendao.GreenDaoManager;
import com.framework2.utils.BiuooCollectionUtil;
import com.framework2.utils.BiuooCustomProgressDialogUtils;
import com.framework2.utils.PicToastUtil;
import com.asiainfo.heshanghui.R;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 销售单详情/扫描后的详情页
 *
 * @author Yangjie
 *         className ScanListDetailActivity
 *         created at  2017/3/15  11:30
 */
public class ScanListDetailActivity extends BiuooBaseActivity {
    private UniversalAdapter adapter;
    private ArrayList<ScanInfo> phoneList = new ArrayList<>();
    private int phoneCount, accessoriesCount;
    private ArrayList<ScanInfo> accessoriesList = new ArrayList<>();
    private List<SaleListInfo> saleInfoList = new ArrayList<>();
    private TitleView titleView;
    private RecyclerView recyclerView;
    private View viewHeader1, viewHeader2, footer;
    //footer
    private TextView tv_sell_total;//销售总额
    private TextView tv_sure;//确认销售
    //header
    private EditText et_nick;//用户名
    private Spinner spinner;//联系方式
    private EditText et_phone;//号码
    private EditText et_mark;//备注信息
    //******************************************//SUCCESS_LAYOUT
    private LinearLayout successLayout;
    private TextView tv_profit;
    private TextView tv_order_code;
    private TextView tv_intro;
    private TextView tv_date;
    private boolean success;
    //******************************************
    private int contactType = 0;//联系方式类型
    private DecimalFormat decimalFormat;
    private String phoneTemp, qqTemp, wChatTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_salelist_detail);
        Utils.setTranslucentStatus(this, true);
        Utils.setStatusBarTintColor(this,
                getResources().getColor(R.color.white));
        decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
        initView();
        initData();
    }

    private void initData() {
        initDB();
        refreshTotalPrice();
        initRecyclerView();
    }

    @SuppressWarnings("unchecked")
    private void initDB() {
        accessoriesCount = 0;
        phoneCount = 0;
        accessoriesCount = 0;
        accessoriesList.clear();
        phoneList.clear();
        saleInfoList.clear();
        List list = GreenDaoManager.getInstance().queryEntityList(ScanListDetailActivity.this, ScanInfo.class);
        if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
            int lenth = list.size();
            for (int i = lenth - 1; i >= 0; i--) {
                ScanInfo scanInfo = (ScanInfo) list.get(i);
                if (null != scanInfo) {
                    if (scanInfo.getIsPhone() && !containsPhone(scanInfo) && scanInfo.getCount() > 0) {
                        phoneList.add(scanInfo);
                        phoneCount += scanInfo.getCount();
                    } else if (!scanInfo.getIsPhone() && scanInfo.getCount() > 0) {
//                        if (!containsAccessories(scanInfo)) {
                        accessoriesList.add(scanInfo);
                        accessoriesCount += scanInfo.getCount();
//                        }
                    }
                }
            }
            if (!BiuooCollectionUtil.getInstance().isEmpty(phoneList)) {
                SaleListInfo info = new SaleListInfo();
                info.setList(phoneList);
                info.setCount(Math.max(phoneCount, phoneList.size()));
                info.setExpanded(true);
                info.setName("手机商品");
                info.setType("0");
                saleInfoList.add(info);
            }
            if (!BiuooCollectionUtil.getInstance().isEmpty(accessoriesList)) {
                SaleListInfo info = new SaleListInfo();
                info.setList(accessoriesList);
                info.setCount(Math.max(accessoriesCount, accessoriesList.size()));
                info.setExpanded(true);
                info.setName("配件商品");
                info.setType("1");
                saleInfoList.add(info);
            }
            if (BiuooCollectionUtil.getInstance().isEmpty(saleInfoList)) {
//                ToastUtil.getInstance().showToast("无有效手机或配件");
                finishActivity();
            }
        } else {
            ToastUtil.getInstance().showToast("未选择手机或配件");
            finishActivity();
        }
    }

    private boolean containsAccessories(@NonNull ScanInfo scanInfo) {
        int len = accessoriesList.size();
        for (int i = 0; i < len; i++) {
            if (TextUtils.equals(accessoriesList.get(i).getType(), scanInfo.getType()) && accessoriesList.get(i).getPrice() == scanInfo.getPrice()) {
                accessoriesList.get(i).setCount(accessoriesList.get(i).getCount() + scanInfo.getCount());
//              boolean a=  GreenDaoManager.getInstance().deleteEntity(this,scanInfo);
//                Y.y("containsAccessories:"+a);
//                scanInfo.setType("-1");
                scanInfo.setCount(0);
                accessoriesCount += scanInfo.getCount();
                return true;
            }
        }
        return false;
    }

    private boolean containsPhone(@NonNull ScanInfo scanInfo) {
        int len = phoneList.size();
        for (int i = 0; i < len; i++) {
            if (TextUtils.equals(phoneList.get(i).getImei(), scanInfo.getImei())) {
                return true;
            }
        }
        return false;
    }

    private void initView() {
        titleView = (TitleView) findViewById(R.id.titleView);
        titleView.setTitle("出库确认").setLeftOnClickListener(new BaseOnClickListener() {
            @Override
            protected void onBaseClick(View v) {
                if (!success) {
                    Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, null, true);
                    finishActivity();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(ConstantsME.avoidClear, true);
                    startActivity(ScanActivity.class, bundle);
                } else {
                    goBackHomepage();
                }
            }
        }).setRightVisible(false);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        tv_sell_total = (TextView) findViewById(R.id.tv_sell_total);
        tv_sure = (TextView) findViewById(R.id.tv_sure);
        //successLayout
        successLayout = (LinearLayout) findViewById(R.id.successLayout);
        tv_profit = (TextView) findViewById(R.id.tv_profit);
        tv_order_code = (TextView) findViewById(R.id.tv_order_code);
        tv_intro = (TextView) findViewById(R.id.tv_intro);
        tv_date = (TextView) findViewById(R.id.tv_date);
    }

    private double refreshTotalPrice() {
        double price = 0;
        if (null != tv_sell_total) {
            if (null != phoneList) {
                int len = phoneList.size();
                for (int i = 0; i < len; i++) {
                    ScanInfo info = phoneList.get(i);
                    price += info.getPrice() * info.getCount();
                }
            }
            if (null != accessoriesList) {
                int len = accessoriesList.size();
                for (int i = 0; i < len; i++) {
                    ScanInfo info = accessoriesList.get(i);
                    price += info.getPrice() * info.getCount();
                }
            }
            decimalFormat.applyPattern("0.00");
            tv_sell_total.setText("合计: ¥ " + decimalFormat.format(price));
        }
        return price;
    }

    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        decimalFormat.applyPattern("0.00");
        if (adapter == null) {
            adapter = new UniversalAdapter<SaleListInfo>(ScanListDetailActivity.this, R.layout.listitem_salelist, saleInfoList) {
                @Override
                protected void getItemView(UniversalViewHolder viewHolder, final SaleListInfo info, final int position) {
                    String count = "共" + info.getCount() + (TextUtils.equals(info.getType(), "0") ? "台" : "件");
//                    SpannableString spannableString = new SpannableString(count);
//                    spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color._red)), 1, spannableString.length() - 1,
//                            Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    viewHolder.setText(R.id.tv_count, count);
                    viewHolder.setText(R.id.tv_name, TextUtils.isEmpty(info.getName()) ? "名称未知" : info.getName());
                    ImageView iv_icon = viewHolder.getView(R.id.iv_icon);
                    if (TextUtils.equals(info.getType(), "0")) {
                        iv_icon.setImageResource(R.mipmap.office_icon_store_phone);
                    } else if (TextUtils.equals(info.getType(), "1")) {
                        iv_icon.setImageResource(R.mipmap.office_icon_store_accessories);
                    }

                    ImageView iv_arrow = viewHolder.getView(R.id.iv_arrow);
                    iv_arrow.setImageResource(info.isExpanded() ? R.mipmap.arrow_up : R.mipmap.arrow_down);//是否展开
                    viewHolder.getView(R.id.rootView).setTag(R.id.saleListExpancedTag, info);
                    viewHolder.getView(R.id.rootView).setOnClickListener(onclickExpandListener);

                    RecyclerView recyclerViewChild = viewHolder.getView(R.id.recyclerViewChild);
                    recyclerViewChild.setVisibility(info.isExpanded() ? View.VISIBLE : View.GONE);
                    if (info.getList().size() > 0) {
                        CustomLinearLayoutManager linearLayoutManager = new CustomLinearLayoutManager(ScanListDetailActivity.this);
                        linearLayoutManager.setScrollEnabled(false);
                        recyclerViewChild.setLayoutManager(linearLayoutManager);

                        UniversalAdapter adapterChild = new UniversalAdapter<ScanInfo>(ScanListDetailActivity.this, R.layout.listitem_salelist_child, info.getList()) {
                            @Override
                            protected void getItemView(UniversalViewHolder viewHolder, ScanInfo item, int childPosition) {
                                SpannableString spannableString = new SpannableString("¥ " + decimalFormat.format(item.getPrice()) + "元");
                                spannableString.setSpan(new AbsoluteSizeSpan(10, true), 0, 1,
                                        Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                spannableString.setSpan(new AbsoluteSizeSpan(10, true), spannableString.length() - 3, spannableString.length(),
                                        Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                ImageView iv_icon = viewHolder.getView(R.id.iv_icon);
                                TextView tv_name = viewHolder.getView(R.id.tv_name);
                                TextView tv_price = viewHolder.getView(R.id.tv_price);
                                tv_name.setText(TextUtils.isEmpty(item.getName()) ? "名称未知" : item.getName());
                                tv_price.setText(spannableString);
                                try {
                                    Glide.with(ScanListDetailActivity.this).load(item.getImgUrl()).placeholder(R.mipmap.default_icon).error(R.mipmap.default_icon)
                                            .priority(Priority.HIGH).into(iv_icon);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (TextUtils.equals(info.getType(), "0")) {
                                    viewHolder.getView(R.id.tv_count).setVisibility(View.GONE);
                                    viewHolder.getView(R.id.tv_imei).setVisibility(View.VISIBLE);
                                    viewHolder.getView(R.id.tv_params).setVisibility(View.VISIBLE);
                                    viewHolder.setText(R.id.tv_imei, String.valueOf("IMEI:" + item.getImei()));
                                    viewHolder.setText(R.id.tv_params, String.valueOf("颜色: " + item.getColor() + "    存储空间: " + item.getRoom()));
                                } else if (TextUtils.equals(info.getType(), "1")) {
                                    viewHolder.getView(R.id.tv_count).setVisibility(View.VISIBLE);
                                    viewHolder.getView(R.id.tv_imei).setVisibility(View.GONE);
                                    viewHolder.getView(R.id.tv_params).setVisibility(View.GONE);
                                    viewHolder.setText(R.id.tv_count, String.valueOf("X" + item.getCount()));
                                }
                            }
                        };
                        recyclerViewChild.setAdapter(adapterChild);
                    }
                }
            };
        }
        recyclerView.setAdapter(adapter);
        if (adapter.getHeaderCount() <= 0) {
            adapter.addHeaderViewAfterSetAdapter(initHeader1());
//        adapter.addHeaderViewAfterSetAdapter(initHeader2());
        }
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断隐藏软键盘是否弹出
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    //隐藏软键盘
                    Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, null, true);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    /**
     * 初始化第一个header
     *
     * @return view
     */
    private View initHeader1() {
        viewHeader1 = LayoutInflater.from(ScanListDetailActivity.this).inflate(R.layout.inflater_goodslist_header1, null);
        int minWidth = ScreenUtils.getInstance().getScreenWidthPx(ScanListDetailActivity.this);
        viewHeader1.setMinimumWidth(minWidth);

        et_nick = (EditText) viewHeader1.findViewById(R.id.et_nick);
        et_phone = (EditText) viewHeader1.findViewById(R.id.et_phone);
        et_mark = (EditText) viewHeader1.findViewById(R.id.et_mark);
        spinner = (Spinner) viewHeader1.findViewById(R.id.spinner);
        //定义适配器
        String array[] = {"手机号", "QQ号", "微信号"};
        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, R.layout.listitem_contact_type, R.id.tv_contact, array);
//        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter2);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!TextUtils.isEmpty(et_phone.getText())) {
                    if (contactType == 0) {
                        phoneTemp = et_phone.getText().toString();
                    } else if (contactType == 1) {
                        qqTemp = et_phone.getText().toString();
                    } else if (contactType == 2) {
                        wChatTemp = et_phone.getText().toString();
                    }
                }
                contactType = position;
                if (position == 0) {
                    et_phone.setInputType(InputType.TYPE_CLASS_NUMBER);
                    et_phone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                    if (!TextUtils.isEmpty(phoneTemp)) {
                        et_phone.setText(phoneTemp);
                        et_phone.setSelection(phoneTemp.length());
                    } else {
                        et_phone.setText("");
                    }
                } else if (position == 1) {
                    et_phone.setInputType(InputType.TYPE_CLASS_NUMBER);
                    et_phone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
                    if (!TextUtils.isEmpty(qqTemp)) {
                        et_phone.setText(qqTemp);
                        et_phone.setSelection(qqTemp.length());
                    } else {
                        et_phone.setText("");
                    }
                } else if (position == 2) {
                    et_phone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
                    et_phone.setInputType(InputType.TYPE_CLASS_TEXT);
                    if (!TextUtils.isEmpty(wChatTemp)) {
                        et_phone.setText(wChatTemp);
                        et_phone.setSelection(wChatTemp.length());
                    } else {
                        et_phone.setText("");
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        String clientNameCache = PreferencesHelper.getInstance().getStringData(ConstantsME.clientNameCache);
        int clientContactTypeCache = PreferencesHelper.getInstance().getIntData(ConstantsME.clientContactTypeCache);
        String clientContactCache = PreferencesHelper.getInstance().getStringData(ConstantsME.clientContactCache);
        String clientRemarkCache = PreferencesHelper.getInstance().getStringData(ConstantsME.clientRemarkCache);
        if (!TextUtils.isEmpty(clientNameCache)) {
            et_nick.setText(clientNameCache);
            et_nick.setSelection(clientNameCache.length());
        }
        if (!TextUtils.isEmpty(clientContactCache)) {
            et_phone.setText(clientContactCache);
            et_phone.setSelection(clientContactCache.length());
            spinner.setSelection(clientContactTypeCache);
        }
        if (!TextUtils.isEmpty(clientRemarkCache)) {
            et_mark.setText(clientRemarkCache);
            et_mark.setSelection(clientRemarkCache.length());
        }
        return viewHeader1;
    }

    /**
     * 初始化第2个header
     *
     * @return view
     */
    private View initHeader2() {
//        viewHeader2 = LayoutInflater.from(ScanListDetailActivity.this).inflate(R.layout.inflater_goodslist_header2, null);
//        int minWidth = ScreenUtils.getInstance().getScreenWidthPx(ScanListDetailActivity.this);
//        viewHeader2.setMinimumWidth(minWidth);
        return viewHeader2;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

//    /**
//     * 子recyclerView的item点击
//     */
//    private BaseOnClickListener onClickDeleteListener = new BaseOnClickListener() {
//        @Override
//        protected void onBaseClick(View v) {
//            if (null != v.getTag(R.id.saleListTag)) {
//                SaleListInfo item = (SaleListInfo) v.getTag(R.id.saleListTag);
//                if (null != item) {
//                    if ((null != v.getTag(R.id.saleListAdapterTag))) {
//                        UniversalAdapter adapterChild = (UniversalAdapter) v.getTag(R.id.saleListAdapterTag);
//                        if (null != adapterChild) {
//                            if (null != v.getTag(R.id.saleListPositionTag)) {
//                                int position = (int) v.getTag(R.id.saleListPositionTag);
//                                int fatherPosition = (int) v.getTag(R.id.saleListFatherPositionTag);
//                                if (position >= 0) {
//                                    deleteFromDB(item.getId(), item.getType());
//                                    adapterChild.deleteData(position);
//                                    if (adapterChild.getDataItemCount() <= 0) {
//                                        adapter.deleteData(fatherPosition);
//                                        if (adapter.getDataItemCount() <= 0) {
//                                            ToastUtil.getInstance().showToast("数据为空,请添加数据!");
//                                            finishActivity();
//                                        }
//                                    } else {
//                                        adapter.notifyDataSetChanged();
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    };

//    private void deleteFromDB(String imei, String type) {
//        Y.y("deleteFromDB:1" + imei + "  " + type);
//        if (!CollectionUtil.getInstance().isEmpty(list)) {
//            for (int i = 0; i < list.size(); i++) {
//                ScanInfo info = (ScanInfo) list.get(i);
//                if (TextUtils.equals(type, info.getType()) && TextUtils.equals(imei, info.getImei())) {
//                    boolean a = GreenDaoManager.getInstance().deleteEntity(ScanListDetailActivity.this, info);
//                    break;
//                }
//            }
//        }
//    }

    /**
     * 点击 右边展开/收缩箭头
     */
    private BaseOnClickListener onclickExpandListener = new BaseOnClickListener() {
        @Override
        protected void onBaseClick(View v) {
            if (null != v.getTag(R.id.saleListExpancedTag)) {
                SaleListInfo item = (SaleListInfo) v.getTag(R.id.saleListExpancedTag);
                if (null != item) {
                    item.setExpanded(!item.isExpanded());
                    adapter.notifyDataSetChanged();
                }
            }
        }
    };

    private boolean isLegal(EditText et_nick, EditText et_phone, int contactType, List<SaleListInfo> saleInfoList) {
        if (TextUtils.isEmpty(et_nick.getText())) {
            PicToastUtil.showPicToast(ScanListDetailActivity.this, "请输入客户姓名!");
            et_nick.requestFocus();
            Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, et_nick, false);
            return false;
        } else if (contactType == 0 && (TextUtils.isEmpty(et_phone.getText()) || !RegularUtil.getInstance().isMobileNO(et_phone.getText().toString()))) {
            PicToastUtil.showPicToast(ScanListDetailActivity.this, "请输入正确的手机号!");
            et_phone.requestFocus();
            Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, et_phone, false);
            return false;
        } else if (contactType == 1 && (TextUtils.isEmpty(et_phone.getText()) || !RegularUtil.getInstance().isNumberAtLeast6bit(et_phone.getText().toString()))) {
            PicToastUtil.showPicToast(ScanListDetailActivity.this, "请输入正确的QQ号!");
            et_phone.requestFocus();
            Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, et_phone, false);
            return false;
        } else if (contactType == 2 && TextUtils.isEmpty(et_phone.getText())) {
            PicToastUtil.showPicToast(ScanListDetailActivity.this, "请输入正确的微信号!");
            et_phone.requestFocus();
            Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, et_phone, false);
            return false;
        } else if (BiuooCollectionUtil.getInstance().isEmpty(saleInfoList)) {
            PicToastUtil.showPicToast(ScanListDetailActivity.this, "无有效商品信息!");
            Utils.isCloseSoftInputMethod(ScanListDetailActivity.this, et_phone, true);
            return false;
        }
        return true;
    }

    /**
     * 请求生成销售单
     */
    @SuppressWarnings("unchecked")
    private void requestBuildSaleList(@NonNull final String name, @NonNull final int contactType, @NonNull final String contact, @NonNull final String remark, final List<SaleListInfo> saleInfoList) {
        HttpUtil.getInstance().requestBuildSaleList(this, InterfaceConfig.buildSaleList, PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId), name, contactType, contact, remark, saleInfoList, new HttpUtil.OnRequestResult<String>() {
            @Override
            public void onSuccess(String... msg) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                titleView.setRightVisible(false);
                success = true;
                if (null != successLayout) {
                    successLayout.setVisibility(View.VISIBLE);
                    if (null != msg) {
                        DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
                        decimalFormat.applyPattern("0.00");
                        if (TextUtils.isEmpty(msg[0])) {
                            msg[0] = refreshTotalPrice() + "";
                        }
                        try {
                            SpannableString spannableString = new SpannableString(String.valueOf("+" + decimalFormat.format(Double.parseDouble(msg[0])) + "元"));
                            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.black)), spannableString.length() - 1, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(new AbsoluteSizeSpan(14, true), spannableString.length() - 1, spannableString.length(),
                                    Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            tv_profit.setText(spannableString);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        tv_order_code.setText((msg.length > 1 && !TextUtils.isEmpty(msg[1])) ? msg[1] : "暂无订单号");
                        StringBuilder stringBuilder = new StringBuilder();
                        int len = saleInfoList.size();
                        for (int i = 0; i < len; i++) {
                            SaleListInfo saleListInfo = saleInfoList.get(i);
                            if (null != saleListInfo) {
                                ArrayList<ScanInfo> list = saleListInfo.getList();
                                if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
                                    int listLen = list.size();
                                    for (int j = 0; j < listLen; j++) {
                                        ScanInfo scanInfo = list.get(j);
                                        if (TextUtils.isEmpty(stringBuilder.toString())) {
                                            stringBuilder.append(scanInfo.getName());
                                        }else {
                                            stringBuilder.append("、").append(scanInfo.getName());
                                        }
                                    }
                                }
                            }
                        }
                        tv_intro.setText(stringBuilder.toString());
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                        String date = simpleDateFormat.format(new Date());
                        tv_date.setText((msg.length > 3 && !TextUtils.isEmpty(msg[3])) ? msg[3] : date);
                    }
                }
                //删除DB已有的ScanInfo
                GreenDaoManager.getInstance().deleteAll(ScanListDetailActivity.this, ScanInfo.class);
            }

            @Override
            public void onFail(int code, String msg) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "出库异常" : msg);
            }
        });
    }

    private void saveCustomerInfo() {
        PreferencesHelper.getInstance().putInfo(ConstantsME.clientNameCache, TextUtils.isEmpty(et_nick.getText()) ? "" : et_nick.getText().toString());
        PreferencesHelper.getInstance().putInfo(ConstantsME.clientContactCache, TextUtils.isEmpty(et_phone.getText()) ? "" : et_phone.getText().toString());
        PreferencesHelper.getInstance().putInfo(ConstantsME.clientRemarkCache, TextUtils.isEmpty(et_mark.getText()) ? "" : et_mark.getText().toString());

        PreferencesHelper.getInstance().putInfo(ConstantsME.clientContactTypeCache, spinner.getSelectedItemPosition());
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.addGoodsLayout:
                saveCustomerInfo();
                finishActivity();
                Bundle bundle = new Bundle();
                bundle.putBoolean(ConstantsME.avoidClear, true);
                startActivity(ScanActivity.class, bundle);
                break;
            case R.id.tv_sure:
                if (isLegal(et_nick, et_phone, contactType, saleInfoList)) {
                    BiuooCustomProgressDialogUtils.showProcessDialog(this, "正在出库");
                    requestBuildSaleList(et_nick.getText().toString(), contactType + 1, et_phone.getText().toString(), (TextUtils.isEmpty(et_mark.getText()) ? "" : et_mark.getText().toString()), saleInfoList);
                }
                break;
            case R.id.tv_back:
                goBackHomepage(true);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!success) {
                Utils.isCloseSoftInputMethod(this, null, true);
                finishActivity();
                Bundle bundle = new Bundle();
                bundle.putBoolean(ConstantsME.avoidClear, true);
                startActivity(ScanActivity.class, bundle);
            } else {
                goBackHomepage(true);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
